package com.csweimei.rentmanagementtreasure.tenant.viewModel;

import android.app.Application;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.csweimei.rentmanagementtreasure.R;
import com.csweimei.rentmanagementtreasure.adapter.ImageAdapter;
import com.csweimei.rentmanagementtreasure.adapter.RoomAdapter;
import com.csweimei.rentmanagementtreasure.base.AppConfig;
import com.csweimei.rentmanagementtreasure.http.entity.BaseResult;
import com.csweimei.rentmanagementtreasure.http.entity.HouseDetailHzBean;
import com.csweimei.rentmanagementtreasure.http.entity.HouseDetailZzBean;
import com.csweimei.rentmanagementtreasure.pop.ImageShowPop;
import com.csweimei.rentmanagementtreasure.pop.PopEditHouse1;
import com.csweimei.rentmanagementtreasure.pop.PopUtils;
import com.csweimei.rentmanagementtreasure.pop.WarnPop;
import com.csweimei.rentmanagementtreasure.tenant.ui.act.house.AddHzZyHouseActivity;
import com.csweimei.rentmanagementtreasure.tenant.ui.act.house.AddZzZyHouseActivity;
import com.csweimei.rentmanagementtreasure.tenant.ui.act.house.HouseFollowRecordActivity;
import com.csweimei.rentmanagementtreasure.utils.ValidateUtils;
import com.csweimei.rentmanagementtreasure.viewModel.TitleVM;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class HouseDetailHzVM extends TitleVM {

    public ObservableField<HouseDetailHzBean.DataDTO.HlistDTO> houseInfo = new ObservableField<>();
    public ObservableList<HouseDetailHzBean.DataDTO.RoomlistDTO> roomInfo = new ObservableArrayList<>();
    public ObservableField<HouseDetailHzBean.DataDTO.DetailsDTO> leaseInfo = new ObservableField<>();
    public ObservableList<HouseDetailHzBean.DataDTO.DetailsDTO> leaseList = new ObservableArrayList<>();


    public ObservableField<String> houseId = new ObservableField<>();

    public ObservableField<String> roomId = new ObservableField<>();


    public ObservableField<String> type = new ObservableField<>();


    public ObservableField<String> rent = new ObservableField<>();


    public ObservableField<Integer> showLease = new ObservableField<>(View.GONE);

    public HouseDetailHzVM(@NonNull Application application, BaseModel model) {
        super(application, model);
        setTitleText("房源详情");
        setRightIconVisible(View.VISIBLE);
        setRightImg(R.mipmap.title_more);
    }

    RecyclerView recyclerView;
    public void setRecy(RecyclerView imgRecy) {
        recyclerView = imgRecy;
    }

    RecyclerView roomRecy;
    public void setRoomRecy(RecyclerView imgRecy) {
        roomRecy = imgRecy;
    }


    public BindingCommand houseFClick = new BindingCommand(() -> {
        Bundle intent = new Bundle( );
        intent.putInt("id",houseInfo.get().getId());
        intent.putString("type","合租");
        startActivity(HouseFollowRecordActivity.class,intent);
    });

    public BindingCommand addZyClick = new BindingCommand(() -> {
        Bundle intent = new Bundle() ;
        intent.putString("id",houseInfo.get().getId()+"");
        intent.putString("roomid",roomId.get());
        startActivity(AddHzZyHouseActivity.class,intent);
    });

    @Override
    public void onCreate() {
        super.onCreate();
        getHouseData();

    }

    private void getHouseData() {
        Map<String,String> map = AppConfig.getCurMap(model);
        map.put("sid",houseId.get());
        model.cotenancyinfo(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new DisposableObserver<HouseDetailHzBean>() {
                    @Override
                    public void onNext(HouseDetailHzBean o) {
                        if (ValidateUtils.isNotEmptyObjectOrString(o.getData().getHlist())){
                            houseInfo.set(o.getData().getHlist());
                            setImgRecy(houseInfo.get().getImgsrc());
                        }

                        if (ValidateUtils.isNotEmptyObjectOrString(o.getData().getRoomlist())){
                            roomInfo.addAll(o.getData().getRoomlist());
                            setRoomData(o.getData().getRoomlist());
                        }


                        if (ValidateUtils.isNotEmptyObjectOrString(o.getData().getDetails())
                        && o.getData().getDetails().size() > 0){
                            if (ValidateUtils.isNotEmptyString(o.getData().getDetails().get(0).getUname())){
                                leaseList.addAll(o.getData().getDetails());
                                setLease();
                            }

                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void setRoomData(List<HouseDetailHzBean.DataDTO.RoomlistDTO> roomlist) {
        rent.set(roomlist.get(0).getRent());
        roomId.set(roomlist.get(0).getId()+"");

        RecyclerView.LayoutManager manager = new LinearLayoutManager(mActivity,LinearLayoutManager.HORIZONTAL,false);
        roomRecy.setLayoutManager(manager);

        RoomAdapter roomAdapter = new RoomAdapter();
        roomAdapter.setList(roomlist);
        roomRecy.setAdapter(roomAdapter);


        roomAdapter.addChildClickViewIds(R.id.item);
        roomAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            roomAdapter.setSel(position);
            rent.set(roomlist.get(position).getRent());
            roomId.set(roomlist.get(position).getId()+"");
            setLease();
        });




    }

    private void setLease() {
        if (leaseList.size() > 0){
            for (HouseDetailHzBean.DataDTO.DetailsDTO bean :leaseList) {
                if ((bean.getRid()+"").equals(roomId.get())){
                    showLease.set(View.VISIBLE);
                    leaseInfo.set(bean);
                }else {
                    showLease.set(View.GONE);
                }
            }
        }
    }


    private void setImgRecy(String imgsrc) {
        List<String> list = new ArrayList<>();
        if (imgsrc.contains(",")){
            list.addAll(Arrays.asList(imgsrc.split(",")));
        }else {
            list.add(imgsrc);
        }
        ImageAdapter imageAdapter = new ImageAdapter();
        imageAdapter.setList(list);
        imageAdapter.addChildClickViewIds(R.id.img);
        imageAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            showImgPop(imageAdapter.getData().get(position));
        });
        recyclerView.setAdapter(imageAdapter);

    }

    private void showImgPop(String s) {
        ImageShowPop imageShowPop = new ImageShowPop(mActivity,s);
        PopUtils.showPop(mActivity,imageShowPop,false);
    }

    /**
     * 设置房源状态
     * @param status
     */
    public void setHouseStatus( String status){
        Map<String,String> map = new HashMap<>();
        map.put("userid",model.getLoginInfo().getData().getUser_id());
        map.put("sid",houseId.get());
        map.put("roomid", roomId.get());
        map.put("status",status);
        model.housingstatic(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {})
                .subscribe(new DisposableObserver<BaseResult>() {
                    @Override
                    public void onNext(BaseResult bean) {
                        if (bean.issucc){
                            onCreate();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    @Override
    protected void rightIconOnClick() {
        super.rightIconOnClick();

        PopEditHouse1 popEditHouse = new PopEditHouse1(mActivity);
        popEditHouse.setSelBack(x -> {
            if (x.getName().equals("删除")){
                ShowDelHouse();
            }else {
                String status;
                switch (x.getName()){
                    case "签约中":
                        status = "1";
                        break;
                    case "不可用":
                        status = "2";
                        break;
                    default:
                        status = "0";
                        break;

                }
                setHouseStatus(status);
            }

        });
        popEditHouse.setSelId(houseId.get());
        popEditHouse.setRoomId(roomId.get());
        popEditHouse.setSelType("合租");
        PopUtils.showPop(mActivity, popEditHouse,false);
        popEditHouse.setShareView(shareView);
    }

    private void ShowDelHouse() {
        WarnPop pop = new WarnPop(mActivity, "温馨提示", "房屋删除之后，将无法恢复，是否确认继续删除?", new WarnPop.OnSelCallBack() {
            @Override
            public void onCallBack(String s) {
                delHouse();
            }
        });
        PopUtils.showPop(mActivity,pop,true);
    }

    private void delHouse() {
        Map<String,String> map = AppConfig.getCurMap(model);
        map.put("housingID",houseId.get());
        model.delete_housing(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new DisposableObserver<BaseResult>() {
                    @Override
                    public void onNext(BaseResult o) {
                        if (o.issucc){
                            ToastUtils.showShort(o.msg);
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    ViewGroup shareView;
    public void setShare(LinearLayout view) {
        shareView = view;
    }
}
